package cn.glenn._03vehicle.base.filter;

import cn.glenn._03vehicle.pojo.vo.UserVO;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.http.HttpResponse;

@Slf4j
@WebFilter(filterName = "loginCheckFilter",urlPatterns = ("/v1/vehicle/*"))
public class LoginCheckFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.debug("过滤器初始化");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.debug("进入登录过滤器....");
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpSession session = request.getSession();
        UserVO user = (UserVO)session.getAttribute("user");
        if (user != null) {
            filterChain.doFilter(request, response);//有此行代码代表放行，无此行代码代表拦截
        }else {
            response.sendRedirect("/login.html");
        }
    }

    @Override
    public void destroy() {
        log.debug("过滤器销毁");
    }
}
